import { applyMiddleware, legacy_createStore as createStore, combineReducers, } from 'redux'
import { thunk } from 'redux-thunk'
/**
 * 根据配置创建一个仓库
 */
function configureStore(options = {}) {
  const {
    reducer, // reducer 处理器函数
    middleware, // 中间件组成的数组
    preloadedState, // 初始状态
  } = options

  let rootReducer;
  if(typeof reducer === 'function') {
    rootReducer = reducer
  } else {
    // 合并多个子 reducer 处理函数成一个总 reducer 处理函数
    rootReducer = combineReducers(reducer)
  }

  // 默认的中间件组成的数组
  const defaultMiddlewares = () => [thunk]

  // 获取中间件组成的数组
  const middlewares = typeof middleware === 'function' ?
    middleware(defaultMiddlewares) :
    defaultMiddlewares()

  // 配置中间件
  // 创建仓库的 store
  // reducer 处理函数和仓库状态
  const store = applyMiddleware(...middlewares)(createStore)(rootReducer, preloadedState)

  return store
}

export default configureStore
